//
//  WmcHtml5FeedBackVM.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/10/18.
//

import Foundation
import HandyJSON

// MARK: - [WmcHtml5VM]

class WmcHtml5VM: WmcBaseVM {
    // Internal

    /// 路径
    var path: Html5Path?
    /// 参数
    var parameters: [String: String]?
    /// 问题类型
    var questionType: WmcQuestionType?

    /// 构造器
    /// 考虑是否需要改造基类, 限制太死，构造方法很有必要，这些属性 应该全为let 或 private, 不同的构造方法可对应不同的场景，此放不太好
//    init(path: Html5Path,parameters: [String: String]?,questionType: WmcQuestionType?) {
//        self.path = path
//        self.parameters = parameters
//        self.questionType = questionType
//    }

    override func config() {}

    /// 构建 request
    /// - Parameter questionType: 问题类型
    /// - Returns: request对象
    func requestBuilder(questionType: WmcQuestionType = .None) -> URLRequest {
        let url = self.getURLString()
        var param = [String: String]()
        // 有参数使用外部参数，没有使用默认的
        if let parameters = parameters {
            param = parameters
        } else {
            param = self.createDefaultParameters(questionType: questionType)
        }
        // 处理参数
        var urlComponents = URLComponents(string: url)
        var queryItems = [URLQueryItem]()
        for (key, value) in param {
            queryItems.append(URLQueryItem(name: key, value: value))
        }
        queryItems.append(URLQueryItem(name: "headers", value: self.createDefaultHeaders().jsonStringRepresentaiton))
        urlComponents?.queryItems = queryItems
        let request = URLRequest(url: (urlComponents?.url)!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
        return request
    }

    // Private

    /// 获取url
    /// - Returns: url stirng
    private func getURLString() -> String {
        let baseUrl = YPWmcManager.shared.environmentType.feedBackH5_url
        let url = baseUrl + (self.path?.rawValue ?? "")
        return url
    }

    /// 创建默认 query参数
    /// - Parameter questionType: 默认问题类型
    /// - Returns: query参数
    private func createDefaultParameters(questionType: WmcQuestionType = .None) -> [String: String] {
        var params: [String: String] = [:]
        // ids
        params["configId"] = "1"
        params["entryId"] = "2"
        params["appId"] = YPWmcManager.shared.appId
        // 来源
        params["resource"] = YPWmcManager.shared.platform.info.sourceField
        params["tenatId"] = "\(WmcLoginManager.shared.wmcAccountModel?.memberId ?? 0)"
        // 问题类型
        params["classificationId"] = questionType.rawValue
        // 安全区域高度
        params["top"] = "\(Int(Wmc_safeAreaTop))"
        params["bottom"] = "\(Int(Wmc_safeAreaBottom))"
        params["session"] = WmcLoginManager.shared.yupaoAccountModel?.token
        params["uid"] = WmcLoginManager.shared.yupaoAccountModel?.userId
        return params
    }

    /// 创建默认header参数
    /// - Returns: header 参数
    private func createDefaultHeaders() -> [String: String] {
        var headers: [String: String] = [:]
        headers["source"] = YPWmcManager.shared.platform.info.sourceField
        headers["packagename"] = Bundle.main.bundleIdentifier ?? ""
        headers["business"] = YPWmcManager.shared.platform.info.business
        headers["channel"] = "apple store"
        let jv = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown"
        headers["packageversion"] = jv
        headers["deviceId"] = WmcMediaRequest.uuid
        headers["appVersion"] = jv
        return headers
    }
}

extension WmcHtml5VM {
    /// 问题类型（水印相机反馈问题类型）
    enum WmcQuestionType: String {
        case WatermarkType = "水印问题"
        case LocatingType = "定位问题"
        case None = ""
    }

    /// html5 页面 path(路径)
    enum Html5Path: String {
        // 意见反馈
        case feedback = "/feedback/add"

        var title: String {
            switch self {
            case .feedback:
                return "意见反馈"
            }
        }
    }
}

extension Dictionary {
    var jsonStringRepresentaiton: String? {
        guard let theJSONData = try? JSONSerialization.data(withJSONObject: self,
                                                            options: [.prettyPrinted]) else {
            return nil
        }

        return String(data: theJSONData, encoding: .ascii)
    }
}
